//html编码，字符串转为实体
function htmlEncodeByRegExp(str) {
    var temp = "";
    if (str.length == 0) return "";
    temp = str.replace(/&/g, "&amp;");
    temp = temp.replace(/</g, "&lt;");
    temp = temp.replace(/>/g, "&gt;");
    // temp = temp.replace(/\s/g, "&nbsp;");
    // temp = temp.replace(/\'/g, "&#39;");
    // temp = temp.replace(/\"/g, "&quot;");
    return temp;
}
//html实体解码，实体转为字符串。
function htmlDecodeByRegExp(str) {
    var temp = "";
    if (str.length == 0) return "";
    temp = str.replace(/&amp;/g, "&");
    temp = temp.replace(/&lt;/g, "<");
    temp = temp.replace(/&gt;/g, ">");
    temp = temp.replace(/&nbsp;/g, " ");
    temp = temp.replace(/&#39;/g, "'");
    temp = temp.replace(/&quot;/g, "\"");
    return temp;
}

function calculateTimeDifference(timeString, now_time) {
    const parsedDate = new Date(timeString);
    const currentDate = new Date(now_time) || new Date();
    // 计算时间差（毫秒）
    const timeDifference = currentDate - parsedDate;
    return timeDifference;
}

function calculateTimeDifferenceDesc(timeDifference) {
    // 将时间差转换为天、小时、分钟和秒
    const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
    // 格式化输出
    let timeDifferenceString = "";
    if (days > 0) {
        timeDifferenceString += `${days} 天 `;
    }
    if (hours > 0) {
        timeDifferenceString += `${hours} 小时 `;
    }
    if (minutes > 0) {
        timeDifferenceString += `${minutes} 分钟 `;
    }
    timeDifferenceString += `${seconds} 秒`;
    timeDifferenceString += "前";
    return timeDifferenceString;
}


function truncateString(inputString, maxLength = 200) { // 截断字符串
    // 如果输入字符串的长度小于或等于maxLength，则直接返回
    if (inputString.length <= maxLength) {
        return inputString;
    }
    // 否则，返回截断后的字符串，并在末尾添加省略号
    return inputString.substring(0, maxLength - 3) + '...';
}


export { htmlEncodeByRegExp, htmlDecodeByRegExp, calculateTimeDifference, calculateTimeDifferenceDesc, truncateString };